import numpy as np
import pandas as pd
import os
import joblib
from collections import Counter
from datetime import datetime
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
import gc
import warnings
from pylab import mpl
from sklearn.model_selection import *
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.metrics import roc_curve, roc_auc_score
from xgboost import XGBClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
import os
os.environ['JOBLIB_TEMP_FOLDER'] = r'C:\temp\joblib_tmp'

# 设置显示中文字体
plt.rcParams['font.sans-serif'] = ['PingFang SC', 'SimHei', 'Songti SC']
plt.rcParams['axes.unicode_minus'] = False
# 设置正常显示符号
warnings.filterwarnings('ignore')

df_train = pd.read_csv('../../data/processed/train_v1.csv')
Y = df_train['label']
X = df_train.drop(['user_id', 'merchant_id', 'label'], axis=1)
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.25, random_state=10)

# 设置随机森林参数搜索空间
param_grid = {
    'n_estimators': [200],         # 树的数量
    'max_depth': [10],          # 树的最大深度
    'min_samples_split': [2],     # 节点分裂最小样本数
    'min_samples_leaf': [1],       # 叶子节点最小样本数
    'max_features': ['sqrt']      # 每次分裂使用的特征数量
}

# 初始化随机森林分类器
rf = RandomForestClassifier(random_state=42)

# 使用 GridSearchCV 进行网格搜索
grid_search = GridSearchCV(estimator=rf,
                           param_grid=param_grid,
                           scoring='roc_auc',
                           cv=3,
                           n_jobs=-1,
                           verbose=1)

# 开始训练
grid_search.fit(X_train, y_train)

# 获取最佳模型
best_rf = grid_search.best_estimator_

# 预测结果和概率
y_pred = best_rf.predict(X_test)
y_proba = best_rf.predict_proba(X_test)[:, 1]

# 计算 AUC 和准确率
auc = roc_auc_score(y_test, y_proba)
acc = accuracy_score(y_test, y_pred)

# 输出评估结果
print("✅ 最佳参数：", grid_search.best_params_)
print("🏆 最佳交叉验证 AUC 值：%.4f" % grid_search.best_score_)
print("🔍 测试集 AUC 值：%.4f" % auc)
print("🎯 测试集准确率：%.4f" % acc)

# 保存模型
joblib.dump(best_rf, '../../model/random_forest_best.pkl')

# 绘制 ROC 曲线
fpr, tpr, _ = roc_curve(y_test, y_proba)
plt.figure(figsize=(8, 6))
plt.plot(fpr, tpr, color='blue', label=f'ROC Curve (AUC = {auc:.4f})')
plt.plot([0, 1], [0, 1], 'k--')  # 对角线
plt.title('ROC Curve for Random Forest')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.legend(loc='lower right')
plt.grid(True)
plt.show()
